#!/usr/bin/env bash
# Klipper install script
# Script that installs Klipper
# Written by Raymond Himle and Stefan Dej
# Thanks to KevinOConnor
# GPL V3
########


# Source error handling, leave this in place
set -x
set -e

source /common.sh
install_cleanup_trap

unpack /filesystem/root /

echo "Installing Klipper"

apt update
apt install wget git gpiod -y

# Packages for python cffi
apt install virtualenv python-dev libffi-dev build-essential -y

# kconfig requirements
apt install libncurses-dev -y

# hub-ctrl
apt install libusb-dev -y

# AVR chip installation and building
apt install avrdude gcc-avr binutils-avr avr-libc -y
apt install stm32flash dfu-util libnewlib-arm-none-eabi -y
apt install gcc-arm-none-eabi binutils-arm-none-eabi libusb-1.0-0 -y

#Make sure user pi has access to serial ports
usermod -a -G tty pi
usermod -a -G dialout pi

# clone klipper repo
cd /home/pi
gitclone KLIPPER_REPO klipper

[ ! -d /home/pi/klipper_config ] && su -c "mkdir /home/pi/klipper_config" - pi
[ ! -d /home/pi/klipper_logs ] && su -c "mkdir /home/pi/klipper_logs" - pi

# create python virtualenv and install klipper requirements
su -c "virtualenv -p python2 ${KLIPPER_PYTHON_DIR}" - pi
su -c "${KLIPPER_PYTHON_DIR}/bin/pip install -r ${KLIPPER_SRC_DIR}/scripts/klippy-requirements.txt" - pi

# enable systemd service
systemctl_if_exists enable klipper.service

# Run installation steps defined above
